package cn.wen233.srpc.basic.utils;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池 工具类
 *
 * @author wenei
 * @date 2021-10-28 20:35
 */
public class ThreadPoolUtils {

    private static class DefaultFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);

        private AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(false);
            thread.setName("sunglowPool-" + poolNumber.getAndIncrement() + "-thread-" + threadNumber.getAndIncrement());
            return thread;
        }
    }

    public static ExecutorService newCoreThreadPool() {
        return new ThreadPoolExecutor(0, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10), new DefaultFactory());
    }

    public static ExecutorService newSingleThreadPool() {
        return new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), new DefaultFactory());
    }
}
